﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Xml.Linq;

namespace Infrastructure.Aspect.Dynamic
{
    public class CustomXmlExpandoObject : DynamicObject
    {


        Dictionary<string, object> dictionary = new Dictionary<string, object>();
           
        public int Count
        {
            get
            {
                return dictionary.Count;
            }
        }

        public CustomXmlExpandoObject()
        { }

        public object Id { get; set; }

        public object CreatedBy { get; set; }

        public CustomXmlExpandoObject Build(string key, XElement value)
        {
            if (value == null) return this;            
            dictionary.Add(key.ToLower(), value.ToString());
            return this;
        }
        public CustomXmlExpandoObject Build(string key, object value)
        {
            if (value == null) return this;
            dictionary.Add(key.ToLower(), value);
            return this;
        }
        public CustomXmlExpandoObject BString(string key, XElement value)
        {
            if (value == null) return this;
            dictionary.Add(key.ToLower(), value.Value.ToString());
            return this;
        } 
        public CustomXmlExpandoObject BGuid(string key, XElement value)
        {
            if (value == null) return this;
            if (string.IsNullOrEmpty(value.Value)) return this;
            dictionary.Add(key.ToLower(), Guid.Parse(value.Value));
            return this;
        }


        public object GetMember(string key)
        {
            if (this.dictionary.ContainsKey(key.ToLower()))
                return this.dictionary[key.ToLower()];
            else
                return null; 
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {           
            
            string name = binder.Name.ToLower();           
            var has = dictionary.TryGetValue(name, out result);
            if (!has)
            {
                if ( binder.ReturnType.Name == typeof(String).Name)
                {
                    result = string.Empty; 
                }
                else if (binder.ReturnType.Name == typeof(int).Name)
                {
                    result = 0;
                }
                else
                    result = string.Empty;  
            }
             
            return true;
        }        
        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            dictionary[binder.Name.ToLower()] = value;
            return true;
        }
    }
}
